'use client';
import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Tag,
  Modal,
  Form,
  message,
  Typography,
  Divider,
  Row,
  Col,
  Space,
  DatePicker,
  Statistic,
  Alert,
  List,
  Checkbox
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, FilterOutlined, BarChartOutlined, PieChartOutlined, UserOutlined, FileTextOutlined, AlertOutlined } from '@ant-design/icons';
import { likeService, type Like as ServiceLike } from '@/service/like.service';

const { Title, Text, Paragraph } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

interface LikeRecord extends ServiceLike {
  articleId?: number;
  articleTitle?: string;
  userName?: string;
  ipAddress?: string;
  userAgent?: string;
  isAbnormal?: boolean;
  abnormalReason?: string;
}

interface ArticleLikeStat {
  articleId: number;
  articleTitle: string;
  likeCount: number;
  userCount: number;
  dailyIncrease: number;
  weeklyTrend: number[];
}

interface UserLikeStat {
  userId: number;
  userName: string;
  likeCount: number;
  articleCount: number;
  recentActivity: string[];
}

const LikeManagement: React.FC = () => {
  // 状态定义
  const [likeRecords, setLikeRecords] = useState<LikeRecord[]>([]);
  const [filteredRecords, setFilteredRecords] = useState<LikeRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedArticle, setSelectedArticle] = useState<string>('all');
  const [selectedUser, setSelectedUser] = useState<string>('all');
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);
  const [showAbnormalOnly, setShowAbnormalOnly] = useState(false);
  const [articleStats, setArticleStats] = useState<ArticleLikeStat[]>([]);
  const [userStats, setUserStats] = useState<UserLikeStat[]>([]);
  const [abnormalActivities, setAbnormalActivities] = useState<LikeRecord[]>([]);
  
  // 获取文章列表（用于筛选）
  const [articles, setArticles] = useState<Array<{ id: number; title: string }>>([]);
  
  // 获取用户列表（用于筛选）
  const [users, setUsers] = useState<Array<{ id: number; name: string }>>([]);

  // 获取点赞记录列表
  const fetchLikeRecords = async () => {
    setLoading(true);
    try {
      const response = await likeService.getLikeList({
        page: 1,
        pageSize: 500
      });
      
      // 转换为前端需要的格式
      const likesData = response.data.map(like => ({
        ...like,
        userName: like.username || '匿名用户',
        articleId: like.targetId,
        articleTitle: like.targetTitle || `${like.targetType === 'article' ? '文章' : '评论'} #${like.targetId}`,
        ipAddress: '127.0.0.1', // 后端如果有IP字段可以映射
        userAgent: 'Mozilla/5.0', // 后端如果有UA字段可以映射
        isAbnormal: false, // 后端如果有异常标识可以映射
        abnormalReason: undefined
      }));
      
      setLikeRecords(likesData);
      setFilteredRecords(likesData);
    } catch (error) {
      console.error('获取点赞记录失败:', error);
      message.error('获取点赞记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLikeRecords();
  }, []);

  // 筛选点赞记录
  useEffect(() => {
    let result = [...likeRecords];
    
    // 按文章筛选
    if (selectedArticle !== 'all') {
      result = result.filter(record => record.articleId.toString() === selectedArticle);
    }
    
    // 按用户筛选
    if (selectedUser !== 'all') {
      result = result.filter(record => record.userId.toString() === selectedUser);
    }
    
    // 按日期范围筛选
    if (dateRange && dateRange[0] && dateRange[1]) {
      const startDate = new Date(dateRange[0]);
      const endDate = new Date(dateRange[1]);
      endDate.setHours(23, 59, 59, 999);
      
      result = result.filter(record => {
        const recordDate = new Date(record.createdAt);
        return recordDate >= startDate && recordDate <= endDate;
      });
    }
    
    // 只显示异常记录
    if (showAbnormalOnly) {
      result = result.filter(record => record.isAbnormal);
    }
    
    // 按搜索文本筛选
    if (searchText) {
      const lowerSearchText = searchText.toLowerCase();
      result = result.filter(record => 
        record.userName.toLowerCase().includes(lowerSearchText) ||
        record.articleTitle.toLowerCase().includes(lowerSearchText) ||
        record.ipAddress.toLowerCase().includes(lowerSearchText)
      );
    }
    
    // 按时间倒序排列
    result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
    
    setFilteredRecords(result);
  }, [likeRecords, searchText, selectedArticle, selectedUser, dateRange, showAbnormalOnly]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 处理日期范围变化
  const handleDateRangeChange = (dates: any, dateStrings: [string, string]) => {
    setDateRange(dateStrings);
  };

  // 计算统计数据
  const totalLikes = likeRecords.length;
  const uniqueUsers = new Set(likeRecords.map(record => record.userId)).size;
  const uniqueArticles = new Set(likeRecords.map(record => record.articleId)).size;
  const abnormalLikes = likeRecords.filter(record => record.isAbnormal).length;
  
  // 计算今日点赞数（模拟数据）
  const today = new Date().toDateString();
  const todayLikes = likeRecords.filter(record => new Date(record.createdAt).toDateString() === today).length;
  
  // 计算本周点赞趋势（模拟数据）
  const weeklyTrend = Array.from({ length: 7 }, () => Math.floor(Math.random() * 100) + 50);

  // 点赞记录列表列配置
  const columns: ColumnsType<LikeRecord> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 120,
      render: (userName: string, record: LikeRecord) => (
        <div>
          <Text style={{ color: '#1890ff' }}>{userName}</Text>
          {record.isAbnormal && (
            <Tag color="red" style={{ marginLeft: '8px' }}>
              异常
            </Tag>
          )}
        </div>
      )
    },
    {
      title: '文章',
      dataIndex: 'articleTitle',
      key: 'articleTitle',
      width: 300,
      ellipsis: true
    },
    {
      title: '点赞时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      width: 150
    },
    {
      title: '异常原因',
      dataIndex: 'abnormalReason',
      key: 'abnormalReason',
      render: (reason?: string) => (
        reason ? (
          <Text type="danger">{reason}</Text>
        ) : (
          <Text type="success">正常</Text>
        )
      )
    },
    {
      title: '用户代理',
      dataIndex: 'userAgent',
      key: 'userAgent',
      ellipsis: true,
      width: 300
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Title level={3}>点赞管理</Title>
      
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {/* 统计卡片 */}
        <Col span={6}>
          <Card title="点赞统计概览" bordered={true}>
            <Statistic title="总点赞数" value={totalLikes} suffix="次" />
            <Divider style={{ margin: '16px 0' }} />
            <Statistic title="今日点赞" value={todayLikes} suffix="次" />
            <Divider style={{ margin: '16px 0' }} />
            <Statistic title="独立用户" value={uniqueUsers} suffix="人" />
            <Divider style={{ margin: '16px 0' }} />
            <Statistic title="点赞文章" value={uniqueArticles} suffix="篇" />
            <Divider style={{ margin: '16px 0' }} />
            <Statistic title="异常点赞" value={abnormalLikes} suffix="次" valueStyle={{ color: '#ff4d4f' }} />
          </Card>
        </Col>
        
        {/* 异常活动提醒 */}
        <Col span={6}>
          <Card 
            title={
              <Space>
                <AlertOutlined style={{ color: '#ff4d4f' }} />
                <span>异常活动提醒</span>
              </Space>
            } 
            bordered={true}
          >
            {abnormalActivities.length > 0 ? (
              <List
                size="small"
                dataSource={abnormalActivities.slice(0, 5)}
                renderItem={item => (
                  <List.Item>
                    <Text type="danger">{item.userName}</Text>
                    <Text style={{ margin: '0 8px' }}>·</Text>
                    <Text ellipsis>{item.abnormalReason}</Text>
                    <Text style={{ margin: '0 8px' }}>·</Text>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      {new Date(item.createdAt).toLocaleDateString()}
                    </Text>
                  </List.Item>
                )}
              />
            ) : (
              <Alert
                message="暂无异常活动"
                description="当前系统运行正常，未检测到异常点赞行为"
                type="success"
                showIcon
                style={{ marginBottom: 0 }}
              />
            )}
          </Card>
        </Col>
        
        {/* 热门文章点赞排行 */}
        <Col span={12}>
          <Card title="热门文章点赞排行" bordered={true}>
            <List
              size="small"
              bordered
              dataSource={articleStats.slice(0, 6)}
              renderItem={(item, index) => (
                <List.Item>
                  <div style={{ width: '24px', textAlign: 'center', marginRight: '16px' }}>
                    <Tag color={index < 3 ? ['red', 'orange', 'green'][index] : 'blue'}>
                      {index + 1}
                    </Tag>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <Text ellipsis>{item.articleTitle}</Text>
                  </div>
                  <div>
                    <Statistic 
                      title="点赞数" 
                      value={item.likeCount} 
                      valueStyle={{ fontSize: '16px' }}
                      suffix=""
                    />
                  </div>
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
      
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {/* 点赞记录列表 */}
        <Col span={24}>
          <Card 
            title="点赞记录列表"
            extra={
              <Space>
                <Search
                  placeholder="搜索用户/文章/IP地址"
                  allowClear
                  onSearch={handleSearch}
                  style={{ width: 250 }}
                />
                <Select
                  placeholder="文章筛选"
                  value={selectedArticle}
                  onChange={setSelectedArticle}
                  style={{ width: 200 }}
                >
                  <Option value="all">全部文章</Option>
                  {articles.map(article => (
                    <Option key={article.id} value={article.id.toString()}>{article.title}</Option>
                  ))}
                </Select>
                <Select
                  placeholder="用户筛选"
                  value={selectedUser}
                  onChange={setSelectedUser}
                  style={{ width: 120 }}
                >
                  <Option value="all">全部用户</Option>
                  {users.map(user => (
                    <Option key={user.id} value={user.id.toString()}>{user.name}</Option>
                  ))}
                </Select>
                <RangePicker onChange={handleDateRangeChange} placeholder={['开始日期', '结束日期']} />
                <Checkbox checked={showAbnormalOnly} onChange={(e) => setShowAbnormalOnly(e.target.checked)}>
                  只看异常
                </Checkbox>
              </Space>
            }
          >
            <Table
              columns={columns}
              dataSource={filteredRecords}
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
              scroll={{ x: 1400 }}
            />
          </Card>
        </Col>
      </Row>
      
      <Row gutter={16}>
        {/* 用户点赞行为分析 */}
        <Col span={12}>
          <Card title="用户点赞行为分析" bordered={true}>
            <List
              size="small"
              bordered
              dataSource={userStats.slice(0, 8)}
              renderItem={(item, index) => (
                <List.Item>
                  <div style={{ width: '24px', textAlign: 'center', marginRight: '16px' }}>
                    <Tag color="blue">{index + 1}</Tag>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                      <Text>{item.userName}</Text>
                      <Text type="secondary">点赞 {item.likeCount} 次，涉及 {item.articleCount} 篇文章</Text>
                    </div>
                    {item.recentActivity.length > 0 && (
                      <div style={{ fontSize: '12px', color: '#999' }}>
                        {item.recentActivity.map((activity, idx) => (
                          <div key={idx}>{activity}</div>
                        ))}
                      </div>
                    )}
                  </div>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        
        {/* 异常点赞检测报告 */}
        <Col span={12}>
          <Card title="异常点赞检测报告" bordered={true}>
            <div style={{ marginBottom: '16px' }}>
              <Alert
                message="检测结果摘要"
                description={`共检测到 ${abnormalLikes} 次异常点赞行为，占总点赞数的 ${((abnormalLikes / totalLikes) * 100).toFixed(2)}%`}
                type="warning"
                showIcon
              />
            </div>
            
            {abnormalActivities.length > 0 ? (
              <div>
                <Text strong>异常行为类型分布：</Text>
                <div style={{ marginTop: '16px', display: 'flex', flexWrap: 'wrap', gap: '16px' }}>
                  {Array.from(new Set(abnormalActivities.map(a => a.abnormalReason))).map((reason, index) => {
                    const count = abnormalActivities.filter(a => a.abnormalReason === reason).length;
                    return (
                      <Tag key={index} color="red" style={{ padding: '12px 8px', fontSize: '14px' }}>
                        {reason}: {count} 次
                      </Tag>
                    );
                  })}
                </div>
                
                <Divider style={{ margin: '16px 0' }} />
                
                <Text strong>建议措施：</Text>
                <ul style={{ marginTop: '8px' }}>
                  <li>对异常用户进行账号审核</li>
                  <li>实施更严格的点赞频率限制</li>
                  <li>增加验证码验证机制</li>
                  <li>监控异常IP地址的活动</li>
                </ul>
              </div>
            ) : (
              <Text type="success">当前系统运行正常，未检测到异常点赞行为</Text>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};



export default LikeManagement;
